<template>
  <div class="container">
    <custom-header
      title="巡检场景管理"
      @synchronization="synchronization"
    ></custom-header>
    <div class="content">
      <div class="filter">
        <el-row>
          <el-form :inline="true" :model="queryParams" label-width="75px">
            <el-col :span="5">
              <el-form-item label="场景名称">
                <el-input
                  class="scrnarioIpt"
                  v-model="queryParams.scenario_name"
                  placeholder="请选择场景名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="场景编号">
                <el-select
                  v-model="queryParams.scenario_no"
                  class="common-style"
                  clearable
                  placeholder="请选择场景编号"
                >
                  <el-option
                    v-for="item in scenarioBox"
                    :key="item.scenario_no"
                    :label="item.scenario_no"
                    :value="item.scenario_no"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="queryParams.createdTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd HH:mm:ss"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="buttons">
              <el-button @click="reset">重置</el-button>
              <el-button type="primary" @click="search">查询</el-button>
            </el-col>
          </el-form>
          <el-col :span="8" class="action">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addpatrolInspection"
              >新增巡检场景</el-button
            >
            <el-button icon="el-icon-refresh" @click="synchronization()"
              >同步巡检场景</el-button
            >
          </el-col>
        </el-row>
      </div>
      <div class="table">
        <customer-table
          :tableInfo="tableInfo"
          @edit="editRow"
          @deleteRow="deleteRow"
          @viewDetails="viewDetails"
        ></customer-table>
      </div>
    </div>
    <el-pagination
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      :current-page="pageNum"
      :page-size="pageSize"
      layout="total,sizes,prev, pager, next, jumper"
      background
      :total="total"
      align="center"
    >
    </el-pagination>
    <div class="alert" v-if="synchronizationVisible === true">
      <p class="synchronization">
        正在场景同步<i class="el-icon-close" @click="close"></i>
      </p>
      <el-progress :percentage="60"></el-progress>
      <p>正在请求数据，大约剩余5s</p>
    </div>

    <el-dialog
      :title="!editRowState ? '新建巡检场景' : '编辑巡检场景'"
      :visible.sync="dialogVisible"
      append-to-body
      custom-class="custom_dialog"
      width="60%"
      :before-close="handleClose"
    >
      <el-row>
        <el-form
          label-width="140px"
          ref="addForm"
          :rules="rules"
          :model="addForm"
        >
          <el-col :span="12">
            <el-form-item label="场景名称" prop="scenario_name">
              <el-input
                v-model="addForm.scenario_name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场景编号" prop="scenario_no">
              <el-input
                v-model="addForm.scenario_no"
                disabled
                placeholder="待同步"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场景地图">
              <el-upload
                class="business-logo-upload img-upload"
                :http-request="uploadBusinessImg"
                action=""
                :show-file-list="false"
                :on-preview="handlePictureCardPreview"
                :on-success="handleCompanylogoSuccess"
                :before-upload="beforeCompanylogoUpload"
                :data="addForm"
                accept="jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF"
              >
                <img
                  :src="addForm.scenario_img"
                  v-if="addForm.scenario_img"
                  class="logo"
                />
                <i v-else class="el-icon-plus logo-uploader-icon"></i>
              </el-upload>
              <br />
              <el-button
                type="primary"
                v-if="addForm.scenario_img"
                @click="handleMapDelete"
                >地图删除</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="patrolInspectionTaskSubmit"
          >提 交</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogImageVisible">
      <img width="100%" :src="addForm.scenario_img" alt="" />
    </el-dialog>


    <!-- 检查是否有场景处理信息 -->
    <div v-if="isEditDogState" class="dog-position">
      <ul>
        <li v-for="(item, index) in diaList" :key="index">
          <i class="el-icon-warning-outline"></i>有新的场景上传，请尽快编辑信息！{{item.created_at}}&emsp;
          <span class="icon-right" @click="handleEditDog(item)"><i class="el-icon-right"></i></span
          >
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import customHeader from "@/pages/Robot/components/CustomHeader.vue";
import customerTable from "@/pages/Robot/components/CustomerTable.vue";
import customFooter from "@/pages/Robot/components/CustomFooter.vue";
import { UploadFileApi } from "@/services/UserPermission";
import { patrolInspectionTaskApi } from "@/services/Robot";
import OSS from "ali-oss";

export default {
  name: "index",
  components: {
    customHeader,
    customerTable,
    customFooter,
  },
  data() {
    return {
      mystateA1: null,
      synchronizationVisible: false,
      queryParams: {
        scenario_name: "",
        scenario_no: "",
        createdTime: "",
      },
      filter: {},
      dialogVisible: false,
      dialogImageVisible: false,
      formList: [
        {
          label: "场景名称",
          prop: "name",
          type: "input",
          placeholder: "请输入场景名称",
        },
        {
          label: "场景编号",
          prop: "number",
          type: "input",
          placeholder: "待同步",
          disabled: true,
        },
        {
          label: "场景地图",
          prop: "map",
          type: "upload",
        },
      ],
      form: {},
      tableInfo: {
        column: [
          {
            label: "序号",
            prop: "index",
            type: "index",
            width: "50",
          },
          {
            label: "场景名称",
            prop: "scenario_name",
            width: "180",
          },
          {
            label: "场景编号",
            prop: "scenario_no",
          },
          {
            label: "场景下任务数",
            prop: "job_num",
            width: "180",
          },
          {
            label: "创建时间",
            prop: "created_at",
            width: "230",
          },
          {
            label: "操作",
            prop: "action",
            type: "PatrolSceneManagement",
            width: "450",
          },
        ],
        data: [],
      },
      addForm: {
        scenario_name: "",
        scenario_no: "",
        imgpath: "",
        scenario_img: "",
      },
      imageUrl: "",
      bucketUrl: "",
      rules: {
        scenario_name: [
          { required: true, message: "请输入场景名称", trigger: "blur" },
        ],
      },
      pageNum: 1,
      pageSize: 10,
      total: 0,
      editRowState: false,
      scenarioBox: [],
      isEditDogState: false,
      diaList: [
      ],
    };
  },
  created() {
    // this.mystateA1 = this.$notify({
    //   dangerouslyUseHTMLString: true,
    //   message: `<i class="el-icon-s-opportunity" style='background: red;-webkit-background-clip: text;color: transparent;'></i>
    //       <span>有新的场景上传，请尽快同步信息！</span>
    //       <span>2022-11-22 10:45:06</span>
    //       <i class="el-icon-arrow-right"
    //          id="messageTrack" style='margin-left:10px'></i>`,
    //   duration: 0,
    // });
  },
  mounted() {
    document.addEventListener("mouseup", (e) => {
      let _track = document.getElementById("messageTrack");
      if (_track) {
        if (_track.contains(e.target)) {
          this.synchronization();
          this.mystateA1.close();
        }
      }
    });
    this.patrolInspectionTaskList();
    this.handleSelect();
    this.handleIsEditDogList();
  },
  methods: {
    handleEditDog(obj) {
      this.editRow(obj);
    },
    // 场景是否是需要编辑
    handleIsEditDogList() {
      patrolInspectionTaskApi.needEditList().then((res) => {
        if (res.code == 0) {
          console.log(res, "res1111");
          if (Array.isArray(res.data.list) && res.data.list.length !== 0) {
            this.diaList = res.data.list
            this.isEditDogState = true;
          }else {
            this.isEditDogState = false;
          }
        }
      });
    },
    /**
     * 新增重置表单
     */
    addpatrolInspection() {
      this.dialogVisible = true;
      this.editRowState = false;
      this.addForm.scenario_img = "";
      this.addForm.imgpath = "";
      this.$refs.addForm.resetFields();
    },
    /**
     * 地图删除
     */
    handleMapDelete() {
      this.addForm.scenario_img = "";
      this.addForm.imgpath = "";
    },
    /**
     * 提交新建巡检场景
     */
    patrolInspectionTaskSubmit() {
      this.$refs.addForm.validate((valid, object) => {
        if (valid) {
          delete this.addForm.imgpath
          const params = {
            ...this.addForm,
          };
          console.log(params, this.hour, this.minutes, "params1111");
          patrolInspectionTaskApi
            .scenarioSave({ data: { ...params } })
            .then((res) => {
              console.log(res, "122222res");
              if (res.code == 0) {
                // this.handleGoback();
                this.dialogVisible = false
                this.patrolInspectionTaskList();
                this.handleIsEditDogList();
                if(this.editRowState) {
                  this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                }else {
                  this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                }
                
              }
            })
            .catch((e) => {});
        }
      });
    },
    patrolInspectionTaskList(searchObj) {
      const params = {
        is_page: 1,
        page_size: this.pageSize,
        page: this.pageNum,
        ...searchObj,
      };
      patrolInspectionTaskApi
        .scenarioList({
          params: {
            ...params,
          },
        })
        .then((res) => {
          console.log(res, "res222222");
          if (res.code == 0) {
            if (Array.isArray(res.data.list)) {
              this.tableInfo.data = res.data.list;
              this.pageNum = res.data.page;
              this.pageSize = res.data.page_size;
              this.total = res.data.total_count;
            }
          }
        })
        .catch((e) => {
        });
    },
    uploadBusinessImg(params) {
      let formData = new FormData();
      formData.append("module", "business-img");
      formData.append("pic_file_apk", params.file);
      UploadFileApi.uploadFile({
        data: formData,
      }).then((res) => {
        // console.log(res, 'upload business img')
        if (res.data) {
          this.addForm.scenario_img = res.data.file_path;
          this.addForm.imgpath = res.data.file_name;
        }
        console.log(this.addForm, "companyInfo");
      });
    },
    beforeCompanylogoUpload() {},
    handleCompanylogoSuccess() {},
    handlePictureCardPreview() {
      this.dialogImageVisible = true;
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.pageNum = 1;
      this.patrolInspectionTaskList();
    },
    handlePageChange(page) {
      this.pageNum = page;
      this.patrolInspectionTaskList();
    },
    close() {
      this.synchronizationVisible = false;
    },
    synchronization() {
      this.synchronizationVisible = true;
      const params = {
        flag: 1,
      };
      patrolInspectionTaskApi
        .robotSync({
          data: {
            ...params,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.patrolInspectionTaskList();
            this.synchronizationVisible = false;
          }
        })
        .catch((e) => {
          this.synchronizationVisible = false;
        });
    },
    reset() {
      this.queryParams = {};
      this.patrolInspectionTaskList()
    },
    search() {
      console.log(this.queryParams);
      let start_time = Array.isArray(this.queryParams.createdTime) ? this.queryParams.createdTime[0] : undefined;
      let end_time = Array.isArray(this.queryParams.createdTime) ? this.queryParams.createdTime[1] : undefined;
      delete this.queryParams.createdTime;
      const params = {
        ...this.queryParams,
        start_time,
        end_time,
      };
      this.patrolInspectionTaskList({...params});
    },
    editRow(row) {
      console.log(row);
      this.dialogVisible = true;
      this.editRowState = true;
      this.addForm = row;
      this.addForm.scenario_img = ""
        // "http://hibuilding-new.oss-cn-hangzhou.aliyuncs.com/industry/business-img/pic/chenggong.png";
      // this.addForm.imgpath = "industry/business-img/pic/chenggong.png";
    },
    deleteRow(row) {
      // this.deleteDialogVisible = true
      this.$confirm("确认删除此巡检场景？", "删除巡检场景", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(row, "row");
          const params = {
            scenario_id: row.scenario_id,
          };
          patrolInspectionTaskApi
            .scenarioDelete({
              data: {
                ...params,
              },
            })
            .then((res) => {
              if (res.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.patrolInspectionTaskList();
              }
            })
            .catch((e) => {
              this.patrolInspectionTaskList();
            });
        })
        .catch((e) => {});
    },
    viewDetails(row) {
      this.$router.push({
        path: "/PatrolSceneDetails",
        query: {
          scenario_id: row.scenario_id,
        },
      });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    // 下拉框
    handleSelect() {
      patrolInspectionTaskApi.commonScenarioBox().then((res) => {
        if(res.code == 0) {
          this.scenarioBox = res.data.list
        }
      })
      patrolInspectionTaskApi.commonJobBox().then((res) => {
        if(res.code == 0) {
          this.jobBox = res.data.list
        }
      })
      patrolInspectionTaskApi.commonRobotBox().then((res) => {
        if(res.code == 0) {
          this.robotBox = res.data.list
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.el-input,
.el-select,
.el-date-editor {
  width: 100%;
}

.container {
  .content {
    padding: 24px;

    .filter {
      padding-bottom: 20px;
      .action {
        // padding: 24px 0;

        .el-button:last-child {
          margin-left: 40px;
        }

        .el-button--default {
          color: #1890ff;
          border-color: #1890ff;
        }
      }
      .buttons {
        display: flex;
        flex-wrap: nowrap;
        justify-content: flex-end;
      }
      // display: flex;
      // gap: 40px;

      // .item {
      //   margin-right: 20px;
      //   width: 33%;
      //   display: flex;
      //   align-items: center;

      //   .label {
      //     margin-right: 10px;
      //     font-size: 13px;
      //     color: rgba(0, 0, 0, 0.85);
      //     width: fit-content;
      //     font-weight: bold;
      //   }

      //   .el-input,
      //   .el-select {
      //     min-width: 289px;
      //     flex: 1;
      //   }
      // }

      // .item:last-child {
      //   justify-content: end;
      // }
    }
  }
  .el-button--primary {
    background-color: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }
}

.alert {
  width: 390px;
  height: 178px;
  background-color: rgba(255, 255, 255, 1);
  border: 1px solid rgba(204, 204, 204, 1);
  box-shadow: 0px 0px 4px rgba(153, 153, 153, 0.349019607843137);
  position: fixed;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  border-radius: 4px;
  padding: 12px 8px 0 12px;
  /deep/ .el-progress {
    margin: 34px 0 12px 0;
  }
  .synchronization {
    width: 100%;
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-between;
    align-items: center;
  }
  p {
    font-family: "MicrosoftYaHei", "Microsoft YaHei", sans-serif;
    font-weight: 400;
    font-style: normal;
  }
}

.img-upload {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  &:hover {
    border-color: #409eff;
  }
  .logo-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .logo {
    width: 178px;
    height: 178px;
    display: block;
  }
}

.scrnarioIpt {
  width: 100%;
}

.container {
  position: relative;
}
.dog-position {
  padding: 15px;
  position: absolute;
  top: 20px;
  right: 20px;
  // margin: ;
  height: 100px;
  // border: 1px solid #7f7f7f;
  border-radius: 4px;
  overflow-y: auto;
  background-color: #f2f2f2;
  li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #000;
    padding: 5px 0;
    .icon-right {
      display: inline-block;
      width: 16px;
      height: 16px;
      border-radius: 50%;
      background-color: #000;
      color: #fff;
      font-weight: 700;
      cursor: pointer;
    }
  }
}
</style>
<style lang="scss">
.custom_dialog {
  .el-dialog__header {
    padding: 18px;
    text-align: center;
    background-color: #1890ff;

    .el-dialog__close,
    .el-dialog__title {
      color: white;
      font-weight: bold;
      font-size: 18px;
    }
  }

  .item_list {
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      padding: 0 20px;

      .label {
        width: fit-content;
        font-size: 14px;
        color: rgba(0, 0, 0, 0.85);
      }

      .el-input {
        flex: 1;
      }
    }

    .avatar-uploader {
      .el-upload:hover {
        border-color: #409eff;
      }

      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 293px;
        height: 102px;
        line-height: 102px;
        text-align: center;
      }
    }
  }

  .el-dialog__footer {
    text-align: center;
    padding: 20px 0;

    .el-button--primary {
      margin-left: 50px;
    }
  }
}
</style>
